package com.jack.leetcode.每日一题;

/*** 
 * @author zhangjie
 * @date 2020/5/11 21:31
 */
public class pow {

    public static void main(String[] args) {
        double x = 2.0;
        int n = -2;
        System.out.println(myPow(x, n));
    }

    public static double myPow(double x, int n) {
        double result = 1.0;
        if (x == 1.0) {
            return 1;
        }
        if (n == 0) {
            if (x == 0) {
                return 0;
            } else {
                return 1;
            }
        }
        boolean minus = false;
        if (n < 0 && n != -2147483648) {
            minus = true;
            n = -n;
        }
        while (n != 0) {
            if (n == -2147483648) {
                n++;
                n = -n;
                minus = true;
                result *= x;
            }
            if (n % 2 == 1) {
                result *= x;
            }
            x *= x;
            n /= 2;
        }
        return minus ? 1 / result : result;
    }
}
